package com.alipay.rebate.shop.configuration.shiro.realm;

import com.alipay.rebate.shop.configuration.shiro.token.AdminToken;
import com.alipay.rebate.shop.exceptoin.AuthUserNameNotRightException;
import com.alipay.rebate.shop.pojo.user.customer.UserDto;
import com.alipay.rebate.shop.service.admin.AdminCustomerUserService;
import com.alipay.rebate.shop.service.admin.AdminUserService;
import com.alipay.rebate.shop.utils.EncryptUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AdminShiroRealm extends AuthorizingRealm {

    private final Logger logger = LoggerFactory.getLogger(AdminShiroRealm.class);

    private AdminUserService userService;

    public AdminShiroRealm(AdminUserService userService) {
        this.userService = userService;
        this.setCredentialsMatcher(new HashedCredentialsMatcher(Sha256Hash.ALGORITHM_NAME));
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof AdminToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        logger.debug("Get into AdminShiroRealm");
        AdminToken adminToken = (AdminToken)token;
        logger.debug("AdminAccountToken is :{}", adminToken);
        String userName = adminToken.getUsername();
        logger.debug("account is :{}",userName);
        char[] password = adminToken.getPassword();
        logger.debug("password is: {}",password);
        // get from database
        UserDto user = userService.getUserDtoInfoForAdminLogin(userName);
        if(user == null){
            throw new AuthUserNameNotRightException();
        }
        logger.debug("UserDto is: {}",user);
        return new SimpleAuthenticationInfo(user, user.getEncryptPwd(), ByteSource.Util.bytes(
            EncryptUtil.encryptSalt), "adminAccountRealm");
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
}
